package com.wsz.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.common.Result;
import com.wsz.common.utils.JwtUtil;
import com.wsz.common.utils.MD5;
import com.wsz.system.config.SystemException;
import com.wsz.system.pojo.User;
import com.wsz.system.service.UserService;
import com.wsz.vo.LoginVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags="初始页面")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",loginVo.getUsername());
        User one = userService.getOne(userQueryWrapper);

        if(one == null){
            throw new SystemException(20001,"该用户不存在");
        }

        String password = MD5.encrypt(loginVo.getPassword());
        if(!one.getPassword().equals(password)){
            throw new SystemException(20001,"密码输入错误");
        }

        if(one.getStatus()==0){
            throw new SystemException(20001,"该用户以被封禁");
        }

        String token = JwtUtil.createToken(one.getId(), one.getUsername());

        Map<String,Object> map = new HashMap<>();

        map.put("token",token);

        return Result.ok(map);
    }

    @GetMapping("info")
    public Result info(HttpServletRequest request){

        String token = request.getHeader("token");

        String username = JwtUtil.getUsername(token);

        //根据用户名称获取用户信息（基本信息 和 菜单权限 以及 按钮权限数据）
        Map<String,Object> map = userService.getUserInfo(username);

        return Result.ok(map);
    }
}
